#include <stdio.h>
#include <openssl/x509.h>
#include <openssl/objects.h>
#include <openssl/pem.h>

int main(int argc, char* argv[])
{
    X509 *cert;
    X509_EXTENSION *ext;
    int ext_index;

    // 从文件中加载证书
    FILE *cert_file = fopen("/home/zhahaobing/code/updated_certificate.pem", "r");
    cert = PEM_read_X509(cert_file, NULL, NULL, NULL);
    fclose(cert_file);

    // 查找扩展项的索引
    // ext_index = X509_get_ext_by_NID(cert, NID_basic_constraints, -1);
	
    ext_index = X509_get_ext_by_NID(cert, NID_netscape_comment, -1);

    // 检查是否找到扩展项
    if (ext_index != -1) {
        // 获取扩展项
		printf("ext_index=%d, at line %d.\n", ext_index, __LINE__);
        ext = X509_get_ext(cert, ext_index);

        // 删除扩展项
        X509_EXTENSION *ret = X509_delete_ext(cert, ext_index);
		if (NULL != ret) {
			printf("delete NID_basic_constraints success,at line %d.\n", __LINE__);
		}
		if(ext == ret)
		{
			printf("=======,at line %d.\n", __LINE__);
		}

		// 查找扩展项的索引
		ext_index = X509_get_ext_by_NID(cert, NID_basic_constraints, -1);
		// 检查是否找到扩展项
		if (ext_index != -1) {
				printf("=r3rr==,at line %d.\n", __LINE__);
		}

		// 释放扩展项内存
        X509_EXTENSION_free(ext);
    }

	// // 查找扩展项的索引
	// ext_index = X509_get_ext_by_NID(cert, NID_netscape_comment, -1);

	// // 检查是否找到扩展项
	// if (ext_index != -1) {
	// 	// 获取扩展项
	// 	ext = X509_get_ext(cert, ext_index);
	// 	printf("ext_index=%d, at line %d.\n", ext_index, __LINE__);

	// 	// 删除扩展项
	// 	X509_delete_ext(cert, ext_index);
	// 	printf("delete NID_netscape_comment success.\n");

	// 	// 释放扩展项内存
	// 	X509_EXTENSION_free(ext);
	// }
	
	// // 查找扩展项的索引
	// ext_index = X509_get_ext_by_NID(cert, NID_subject_key_identifier, -1);
	
	// // 检查是否找到扩展项
	// if (ext_index != -1) {
	// 	// 获取扩展项
	// 	ext = X509_get_ext(cert, ext_index);
	// 	printf("ext_index=%d, at line %d.\n", ext_index, __LINE__);

	// 	// 删除扩展项
	// 	X509_delete_ext(cert, ext_index);
	// 	printf("delete NID_subject_key_identifier success.\n");

	// 	// 释放扩展项内存
	// 	X509_EXTENSION_free(ext);
	// }

    // 保存更新后的证书到文件
    FILE *output_file = fopen("updated_certificate01.pem", "w");

	// 查找扩展项的索引
	ext_index = X509_get_ext_by_NID(cert, NID_basic_constraints, -1);
	// 检查是否找到扩展项
	if (ext_index != -1) {
			printf("=r3rr==,at line %d.\n", __LINE__);
	}

    int ret = PEM_write_X509(output_file, cert);
	printf("ret = %d,at line %d.\n", ret, __LINE__);
    fclose(output_file);

    // 释放证书内存
    X509_free(cert);

    return 0;
}

